#pragma once

#include <iostream>
#include <string.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include "log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include "ThreadPool.hpp"
#include "Task.hpp"

namespace server
{
    using namespace std;
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };

    const static uint16_t gport = 8080;
    static const int gbacklog = 5;

    class TcpServer;
    class ThreadData
    {
    public:
        ThreadData(TcpServer* self,int sock)
        :_self(self),_sock(sock)
        {

        }

        ~ThreadData()
        {

        }
    public:
        TcpServer* _self;
        int _sock;
    };

    class TcpServer
    {
    public:
        static void* threadRoutine(void* args)
        {
            pthread_detach(pthread_self());
            ThreadData* td = static_cast<ThreadData*>(args);
            td->_self->serviceIO(td->_sock);
            close(td->_sock);
            delete td;
            return nullptr;
        }

        void serviceIO(int sock)
        {
            char buffer[1024];
            while(1)
            {
                ssize_t n = read(sock,buffer,sizeof(buffer)-1);
                if(n > 0)
                {
                    //目前我们把独到的数据当成字符串
                    buffer[n] = 0;
                    std::cout<<"recv message: "<< buffer <<endl;//打印服务器收到的消息

                    string outbuffer = buffer;
                    outbuffer += "server[echo]";

                    write(sock,outbuffer.c_str(),outbuffer.size());
                }
                else if(n == 0)
                {
                    //代表客户端退出
                    logMessage(NORMAL, "client quit, me too");
                    break;
                }
            }
        }

        TcpServer(const uint16_t &port = gport)
            : _port(port), _listensock(-1)
        {
        }

        void initServer()
        {
            // 1、创建socket文件套接字对象
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                // 封装日志函数
                logMessage(FATAL, "create socket error");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "create socket success");


            // 2、bind绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local,0,sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if(bind(_listensock,(struct sockaddr*)&local,sizeof(local)) < 0)
            {
                logMessage(FATAL,"bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL,"bind socket success");


            //3、设置socket为监听状态，因为必须时时刻刻关心是否向我发送请求
            //listen函数,能一直获取新连接，处理链接请求
            if(listen(_listensock,gbacklog) < 0)
            {
                logMessage(FATAL,"listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL,"listen socket success");

            }

        void start()
        {
            //线程池初始化
            //ThreadPool<Task>::getinstance()->run();


            signal(SIGCHLD,SIG_IGN);
            for(; ;)
            {
                //4、server获取新链接
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                //这里的sock是未来和客户端通信的fd文件描述符
                int sock = accept(_listensock,(struct sockaddr*)&peer,&len);
                if(sock < 0)
                {
                    logMessage(ERROR,"accept error, next");
                    continue;
                }
                logMessage(NORMAL,"accept a new link success");
                cout<< "sock: " << sock <<endl;


                //5、这里就是一个文件描述符，后续的操作就是文件操作
                //demo1
                //也就是read write
                //serviceIO(sock);
                //close(sock);//对于已经使用完的sock,必须关闭,要不然会导致文件描述符泄露


                //demo2 多进程版
                // pid_t id = fork();
                // if(id == 0)
                // {
                //     close(_listensock);

                //     if(fork()>0)
                //     {
                //         exit(0);
                //     }

                //     serviceIO(sock);
                //     close(sock);
                //     exit(0);
                // }
                // else if (id > 0)
                // {
                //     pid_t ret = waitpid(id,nullptr,0);
                //     if(ret > 0)
                //     {
                //         cout<<"waitsuccess: "<< ret <<endl;
                //     }
                // }
                // else
                // {
                //     cout << "fork error" << endl;
                // }


                //demo3 多进程版
                // pid_t id = fork();
                // if(id == 0)
                // {
                //     close(_listensock);
                //     serviceIO(sock);
                //     close(sock);
                //     exit(0);
                // }
                // close(sock);



                //demo3 多线程版
                pthread_t tid;
                ThreadData* td = new ThreadData(this,sock);
                pthread_create(&tid,nullptr,threadRoutine,td);

                //demo4线程池版
                //ThreadPool<Task>::getinstance()->push();
            }
        }

        ~TcpServer()
        {

        }

    private:
        int _listensock;//不是用来通信的，是用来监听，获取新链接的，叫做listen套接字
        uint16_t _port;
    };
}
